package com.liveinstars.quhui.business.interest.repository.persistence;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.liveinstars.quhui.business.interest.repository.po.InterestGroupMember;
import com.liveinstars.quhui.business.interest.repository.mapper.InterestGroupMemberMapper;
import com.liveinstars.quhui.business.interest.repository.facade.IInterestGroupMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liveinstars.quhui.business.interest.service.impl.InterestDomainServiceImpl;
import com.onepiece.shipelves.common.enums.SystemExceptionEnum;
import com.onepiece.shipelves.common.exception.DatabaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 兴趣成员组织 服务实现类
 * </p>
 *
 * @author ting
 * @since 2020-10-16
 */
@Service
public class InterestGroupMemberServiceImpl extends ServiceImpl<InterestGroupMemberMapper, InterestGroupMember> implements IInterestGroupMemberService {
    private final static Logger logger = LoggerFactory.getLogger(InterestGroupMemberServiceImpl.class);
    @Override
    public List<InterestGroupMember> listByUserId(Integer userId, int groupType) {
        try {
            QueryWrapper<InterestGroupMember> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            return this.list(queryWrapper);
        } catch (Exception e) {
            logger.error("listByUserId userId:{} groupType:{} errorMsg:{}",
                    userId, groupType, e.getMessage(), e);
            throw new DatabaseException(SystemExceptionEnum.MYSQL_OPERATING_ERROR);
        }
    }

    @Override
    public Map<Integer, Integer> mapMemberCountByGroupIdList(List<Integer> chatGroupIdList) {
        try {
            Map<Integer, Integer> chatGroupMemberCountMap = Maps.newHashMap();
            QueryWrapper<InterestGroupMember> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("interest_group_id", chatGroupIdList).groupBy("interest_group_id").select("interest_group_id", "count(*) as count");
            List<Map<String, Object>> list = this.listMaps(queryWrapper);
            list.stream().filter(Objects::nonNull)
                    .forEach(map -> chatGroupMemberCountMap.put(Integer.valueOf(String.valueOf(map.get("interest_group_id"))), Integer.valueOf(String.valueOf(map.get("count")))));
            return chatGroupMemberCountMap;
        } catch (Exception e) {
            logger.error("mapMemberCountByGroupIdList chatGroupIdList:{} errorMsg:{}",
                    chatGroupIdList.toString(), e.getMessage(), e);
            throw new DatabaseException(SystemExceptionEnum.MYSQL_OPERATING_ERROR);
        }
    }
}
